import tkinter as tk
from tkinter import ttk, messagebox
import json
import os

class SettingsWindow:
    """设置窗口类，负责应用程序的设置管理"""
    
    def __init__(self, parent):
        """初始化设置窗口"""
        self.parent = parent
        self.settings_window = tk.Toplevel(parent)
        self.settings_window.title("设置")
        self.settings_window.geometry("600x400")
        self.settings_window.resizable(False, False)
        self.settings_window.transient(parent)  # 设置为主窗口的子窗口
        self.settings_window.grab_set()  # 模态窗口
        
        # 加载当前设置
        self.settings = self.load_settings()
        
        # 创建选项卡控件
        self.create_notebook()
    
    def load_settings(self):
        """加载设置文件"""
        # 默认设置
        default_settings = {
            'player': {
                'default_player': '系统默认'
            },
            'database': {
                'path': ''
            },
            'other': {}
        }
        
        # 尝试从文件加载设置
        settings_file = 'settings.json'
        if os.path.exists(settings_file):
            try:
                with open(settings_file, 'r', encoding='utf-8') as f:
                    user_settings = json.load(f)
                    # 合并默认设置和用户设置
                    default_settings.update(user_settings)
            except Exception as e:
                messagebox.showerror("错误", f"加载设置失败: {str(e)}")
        
        return default_settings
    
    def save_settings(self):
        """保存设置到文件（不显示成功提示）"""
        try:
            with open('settings.json', 'w', encoding='utf-8') as f:
                json.dump(self.settings, f, ensure_ascii=False, indent=4)
        except Exception as e:
            messagebox.showerror("错误", f"保存设置失败: {str(e)}")
    
    def create_notebook(self):
        """创建选项卡控件"""
        self.notebook = ttk.Notebook(self.settings_window)
        self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建各个选项卡的框架
        self.basic_frame = ttk.Frame(self.notebook, padding="10")
        self.database_frame = ttk.Frame(self.notebook, padding="10")
        self.other_frame = ttk.Frame(self.notebook, padding="10")
        
        # 添加选项卡
        self.notebook.add(self.basic_frame, text="基础设置")
        self.notebook.add(self.database_frame, text="数据库设置")
        self.notebook.add(self.other_frame, text="其他设置")
        
        # 创建各个选项卡的内容
        self.create_basic_settings()
        self.create_database_settings()
        self.create_other_settings()
        
        # 添加底部按钮
        self.create_bottom_buttons()
    
    def create_basic_settings(self):
        """创建基础设置选项卡内容"""
        # 创建默认播放器设置区域
        player_frame = ttk.LabelFrame(self.basic_frame, text="默认播放器", padding="10")
        player_frame.pack(fill=tk.X, pady=10)
        
        # 播放器选择
        ttk.Label(player_frame, text="选择默认播放器:").pack(anchor=tk.W, pady=5)
        
        # 创建单选按钮组
        self.player_var = tk.StringVar(value=self.settings.get('player', {}).get('default_player', '系统默认'))
        
        # 播放器选项（只有两项：系统默认和自定义）
        players = [
            '系统默认',
            '自定义'
        ]
        
        # 创建单选按钮
        player_radio_frame = ttk.Frame(player_frame)
        player_radio_frame.pack(fill=tk.X, pady=5)
        
        for player in players:
            ttk.Radiobutton(player_radio_frame, text=player, variable=self.player_var, value=player).pack(anchor=tk.W, pady=2)
        
        # 添加自定义选项的输入框和浏览按钮
        self.custom_player_frame = ttk.Frame(player_frame)
        ttk.Label(self.custom_player_frame, text="播放器路径: ").pack(side=tk.LEFT, padx=5)
        self.custom_player_entry = ttk.Entry(self.custom_player_frame, width=40)
        self.custom_player_entry.pack(side=tk.LEFT, padx=5)
        
        # 添加浏览按钮
        browse_button = ttk.Button(self.custom_player_frame, text="浏览...", command=self.browse_player)
        browse_button.pack(side=tk.LEFT, padx=5)
        
        # 加载已保存的自定义播放器路径
        if self.settings.get('player', {}).get('path'):
            self.custom_player_entry.insert(0, self.settings['player']['path'])
        
        # 添加事件绑定，当选择"自定义"时显示输入框和浏览按钮
        def on_player_change(*args):
            if self.player_var.get() == '自定义':
                self.custom_player_frame.pack(anchor=tk.W, pady=5)
            else:
                self.custom_player_frame.pack_forget()
        
        self.player_var.trace_add('write', on_player_change)
        
        # 初始化时检查是否需要显示输入框和浏览按钮
        if self.player_var.get() == '自定义':
            self.custom_player_frame.pack(anchor=tk.W, pady=5)
    
    def create_database_settings(self):
        """创建数据库设置选项卡内容（暂不实现）"""
        # 添加提示信息
        ttk.Label(self.database_frame, text="数据库设置功能正在开发中...").pack(anchor=tk.W, pady=20)
        ttk.Label(self.database_frame, text="敬请期待后续版本更新！").pack(anchor=tk.W)
    
    def create_other_settings(self):
        """创建其他设置选项卡内容（暂不实现）"""
        # 添加提示信息
        ttk.Label(self.other_frame, text="其他设置功能正在开发中...").pack(anchor=tk.W, pady=20)
        ttk.Label(self.other_frame, text="敬请期待后续版本更新！").pack(anchor=tk.W)
    
    def create_bottom_buttons(self):
        """创建底部的确定、应用和取消按钮"""
        button_frame = ttk.Frame(self.settings_window)
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 应用按钮（放在确定按钮右侧）
        apply_button = ttk.Button(button_frame, text="应用", command=self.on_apply)
        apply_button.pack(side=tk.RIGHT, padx=5)
        
        # 确定按钮
        ok_button = ttk.Button(button_frame, text="确定", command=self.on_ok)
        ok_button.pack(side=tk.RIGHT, padx=5)
        
        # 取消按钮
        cancel_button = ttk.Button(button_frame, text="取消", command=self.on_cancel)
        cancel_button.pack(side=tk.RIGHT, padx=5)
    
    def browse_player(self):
        """浏览文件选择播放器程序"""
        from tkinter import filedialog
        file_path = filedialog.askopenfilename(
            title="选择播放器程序",
            filetypes=[("可执行文件", "*.exe"), ("所有文件", "*.*")]
        )
        if file_path:
            self.custom_player_entry.delete(0, tk.END)
            self.custom_player_entry.insert(0, file_path)
    
    def on_apply(self):
        """应用按钮点击事件"""
        # 获取当前已保存的路径（如果存在）
        existing_path = self.settings.get('player', {}).get('path', '')
        
        # 更新设置
        self.settings['player'] = {
            'default_player': self.player_var.get()
        }
        
        # 如果选择了自定义播放器，使用新路径；否则保留原有路径
        if self.player_var.get() == '自定义':
            self.settings['player']['path'] = self.custom_player_entry.get()
        elif existing_path:
            # 保留之前设置的自定义播放器路径
            self.settings['player']['path'] = existing_path
        
        # 保存设置但不关闭窗口
        self.save_settings()
    
    def on_ok(self):
        """确定按钮点击事件"""
        # 应用设置
        self.on_apply()
        
        # 关闭窗口
        self.settings_window.destroy()
    
    def on_cancel(self):
        """取消按钮点击事件"""
        self.settings_window.destroy()